package com.eb.buybuybuy.core.router;

import com.eb.buybuybuy.constant.RequestMethodEnum;
import com.eb.buybuybuy.core.router.bean.RequestRouteEntrance;

import java.util.HashMap;

public class RequestRouter {
    private static HashMap<RequestMethodEnum, HashMap<String, RequestRouteEntrance>> router = new HashMap<>();

    /**
     * 为路由器添加一个路由
     *
     * @param requestMethod 请求方式
     * @param path          路径
     * @param routeEntrance 入口对象(包含调用需要的类和它的方法)
     */
    public static void addRoute(RequestMethodEnum requestMethod, String path, RequestRouteEntrance routeEntrance) {
        // 1 根据请求类型判断
        HashMap<String, RequestRouteEntrance> routerMap = router.get(requestMethod);
        if (routerMap == null) {
            routerMap = new HashMap<>();
        }
        RequestRouteEntrance entrance = routerMap.get(path);
        if (entrance == null) {
            routerMap.put(path, routeEntrance);
        } else {
            System.out.println("有路径重复");
            return;
        }

        router.put(requestMethod, routerMap);
    }

    public static HashMap<RequestMethodEnum, HashMap<String, RequestRouteEntrance>> getRouter() {
        return router;
    }

    public static RequestRouteEntrance matchesRoute(RequestMethodEnum requestMethod, String requestPath) {
        HashMap<String, RequestRouteEntrance> map = router.get(requestMethod);
        if (map == null) {
            return null;
        }
        RequestRouteEntrance entrance = map.get(requestPath);
        if (entrance == null) {
            return null;
        }
        for (String path : map.keySet()) {
            if (requestPath.matches(path)) {
                return map.get(path);
            }
        }
        return null;
    }
}
